﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace BuildCode.Models
{
    internal static class ConvertExt
    {

        internal static List<T> ToList<T>(this DataTable table) where T : class, new()
        {
            Type type = typeof(T);
            List<T> list = new List<T>();
            var pros = type.GetProperties();
            foreach (DataRow row in table.Rows)
            {
                T obj = Activator.CreateInstance(type) as T;
                foreach (var property in pros)
                {
                    if (table.Columns.Contains(property.Name))
                    {
                        object val = row[property.Name];
                        if (val != null && DBNull.Value.Equals(val) == false)
                        {
                            property.SetValue(obj, val.Convert(property.PropertyType));
                        }
                    }
                }
                list.Add(obj);
            }
            return list;
        }

        internal static object Convert(this object value, Type targetType)
        {
            if (value == null)
                return null;

            if (targetType == typeof(string))
                return value.ToString();

            Type type = Nullable.GetUnderlyingType(targetType) ?? targetType;
            if (value.GetType() == type)
            {
                return value;
            }

            if (type == typeof(Guid) && value.GetType() == typeof(string))
            {
                return new Guid(value.ToString());
            }

            if (type.IsEnum)
            {
                type = Enum.GetUnderlyingType(type);
            }

            return System.Convert.ChangeType(value, type);
        }
    }
}